package model

import (
	"jsjb/connect"
)

type AuthRule struct {
	Del    int8   `json:"del"`
	Dot    bool   `json:"dot"`
	IsMenu bool   `json:"isMenu"`
	Hidden bool   `json:"hidden"`
	Weigh  int32  `json:"weigh"`
	Pid    int32  `json:"pid"`
	ID     int32  `json:"iD"`
	Icon   string `json:"icon"`
	Title  string `json:"title"`
	Name   string `json:"name"`
	Status string `json:"status"`
	Path   string `json:"path"`
}

// TreeList 菜单
type TreeList struct {
	Del      int8   `json:"del"`
	Dot      bool   `json:"dot"`
	IsMenu   bool   `json:"isMenu"`
	Hidden   bool   `json:"hidden"`
	Weigh    int32  `json:"weigh"`
	Pid      int32  `json:"pid"`
	ID       int32  `json:"iD"`
	Icon     string `json:"icon"`
	Title    string `json:"title"`
	Name     string `json:"name"`
	Status   string `json:"status"`
	Path     string `json:"path"`
	Children []TreeList
}

func QueryRules(ar AuthRule) (list []TreeList, e error) {
	var rules []AuthRule
	result := connect.DB.Table("auth_rule").Find(&rules)
	e = result.Error
	list = GetMenu(rules, 0)
	return
}

// FormMenu 格式化菜单
func FormMenu(list []AuthRule, pid int32) (formMenu []AuthRule) {
	for _, val := range list {
		if val.Pid == pid {
			if pid == 0 {
				// 顶层
				formMenu = append(formMenu, val)
			} else {
				var children []AuthRule
				child := val
				children = append(children, child)
			}
		}
	}
	return
}

// GetMenu 获取菜单
func GetMenu(menuList []AuthRule, pid int32) []TreeList {
	var treeList []TreeList
	for _, v := range menuList {
		if v.Pid == pid {
			child := GetMenu(menuList, v.ID)
			node := TreeList{
				ID:     v.ID,
				Name:   v.Name,
				Pid:    v.Pid,
				Del:    v.Del,
				Dot:    v.Dot,
				IsMenu: v.IsMenu,
				Hidden: v.Hidden,
				Weigh:  v.Weigh,
				Icon:   v.Icon,
				Title:  v.Title,
				Status: v.Status,
				Path:   v.Status,
			}
			node.Children = child
			treeList = append(treeList, node)
		}
	}
	return treeList
}
